package top.xana.acg.parser

import top.xana.acg.model.Anime
import top.xana.acg.model.Episode
import top.xana.acg.model.HomeBody

/**
 * @Author: root
 * @Date: 2022/2/15 21:13
 * @Description: email: cv4096@qq.com
 */

private const val BASE_URL = "http://www.bimiacg4.net"

class BimiAcgParser : AnimeParser(), SearchInterface, SourceInterface {

    fun getHomeBody(): List<HomeBody> {
        val aList = get(BASE_URL).selectXpath("//div[@class='area-main fl']")
        return aList.map {
            HomeBody(
                label = it.selectXpath("//div/h2/b").text(),
                items = it.selectXpath("//li").map {
                    Anime(
                        title = it.selectXpath("//a").attr("title"),
                        uri = BASE_URL + it.selectXpath("//a").attr("href"),
                        cover = it.selectXpath("//a/img").attr("src"),
                        status = it.selectXpath("//div/p").attr("title"),
                    )
                }
            )
        }
    }

    override fun search(kw: String, p: Int): List<Anime> {
        val uri = "$BASE_URL/vod/search/wd/$kw/page/$p/"
        val alist = get(uri).selectXpath("//div[@class='v_tb']/ul/li")
        return alist.map {
            Anime(
                title = it.selectXpath("//a").attr("title"),
                uri = BASE_URL + it.selectXpath("//a").attr("href"),
                cover = it.selectXpath("//a/img").attr("src"),
                status = it.selectXpath("//div/p").attr("title"),
            )
        }
    }

    override fun detail(uri: String): Anime {
        val row = get(uri).selectXpath("//div[@class='row']")[0]
        val lis = row.selectXpath("//ul/li")
        return Anime(
            title = row.selectXpath("//img").attr("alt"),
            cover = row.selectXpath("//img").attr("src"),
            extra = lis.map {
                it.text()
            }
        )
    }

    override fun source(uri: String): List<List<Episode>> {
        val plist = get(uri).selectXpath("//ul[@class='player_list']")
        return plist.map {
            it.selectXpath("//li/a").map {
                Episode(it.text(), BASE_URL + it.attr("href"))
            }
        }
    }

    override fun favor(uri: String): List<Anime> {
        val alist = get(uri).selectXpath("//div[@class='love-det']/ul/li")
        return alist.map {
            Anime(
                title = it.selectXpath("//a").attr("title"),
                uri = BASE_URL + it.selectXpath("//a").attr("href"),
                cover = it.selectXpath("//a/img").attr("src"),
                status = it.selectXpath("//div/p/span").text(),
                views = it.selectXpath("//div/p/em").text()
            )
        }
    }

    private val iframe = "$BASE_URL/static/danmu/%s.php?url=%s"

    private val errorUrl = "http://"

    private val fs = listOf("pic", "danmakk")

    override fun playUrl(uri: String): String {
        val mt = "\\{\"flag\":\"(.+?)\".*?\"url\":\"(.+?)\".*?\"from\":\"(.+?)\"".toRegex()
            .find(get(uri).html())!!.groupValues

        return getUrl(mt[2], mt[3])
    }

    private fun getUrl(id: String, f: String): String {

        val st = if (f in fs)
            fs[0]
        else if (f == "renrenmi")
            "rrm"
        else "play"

        val ifBody = get(iframe.format(st, id)).html()
        val url = "var url = '(.*?)'".toRegex().find(ifBody)?.groupValues?.get(1)

        if (url?.startsWith("http") == true)
            return url
        else if (url.isNullOrBlank())
            return errorUrl

        return "$BASE_URL/static/danmu/$url"
    }


    private val types = "riman guoman fanzu juchang dianshiju move".split(" ")

    private val orders = listOf("time", "hits", "score")
    /*
        private val urj = "https://www.bimiacg4.net/vodshow/riman--time-%E7%83%AD%E8%A1%80--A---2-%E5%91%A8%E4%B8%80--2021/"
        索引列表
    */

    private val uri = "$BASE_URL/vodshow/%s--%s-%s--%s---%d-%s--%s/"

    private val tab = "$BASE_URL/type/%s/"

    fun tabel(i: Int): List<List<String>> {
        val uri = this.tab.format(types[i])
        val alist = get(uri).selectXpath("//ul[@class='selcet_list']/li")
        return alist.map {
            val cateList = it.selectXpath("//p/span/a").text().split(" ").toMutableList()
            val first = it.selectXpath("//span[1]")[0].text()
            cateList.set(0, first)
            cateList
        }
    }

    /**
     * 分类 索引
     */
    fun category(
        i: Int = 0,
        o: Int = 0,
        type: String = "",
        alpha: String = "",
        p: Int = 1,
        season: String = "",
        year: String = ""
    ): List<Anime> {
        val uri = this.uri.format(types[i], orders[o], type, alpha, p, season, year)
        val alist = get(uri).selectXpath("//div[@class='v_tb']/ul/li")
        return alist.map {
            Anime(
                title = it.selectXpath("//a").attr("title"),
                uri = BASE_URL + it.selectXpath("//a").attr("href"),
                cover = it.selectXpath("//a/img").attr("src"),
                status = it.selectXpath("//div/p/span[1]").text()
            )
        }
    }

    /**
     * 时间表
     */
    fun timeline(): List<List<Anime>> {
        val alist = get(BASE_URL).selectXpath("//ul[@class='tab-cont__wrap']/li")
        return alist.map {
            it.selectXpath("//ul/li").map {
                Anime(
                    title = it.selectXpath("//a[1]").attr("title"),
                    uri = BASE_URL + it.selectXpath("//a[1]").attr("href"),
                    cover = it.selectXpath("//a[1]/div/img").attr("src"),
                    status = it.selectXpath("//span[1]").text()
                )
            }
        }
    }

    /**
     * 排行榜
     */
    fun rank(): List<Pair<String, List<Anime>>> {
        val alist = get("$BASE_URL/label/top/").selectXpath("//div[@class='top-r']/div")
        return alist.map {
            Pair(
                first = it.selectXpath("//div[1]/span/a").attr("title"),
                second = it.selectXpath("//ul[1]/li/h3/a").map {
                    Anime(
                        title = it.attr("title"),
                        uri = BASE_URL + it.attr("href")
                    )
                }
            )
        }
    }
}